<?php

/*
 * Edit by shengxin
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */

namespace api\admin\controller;

use api\mall\model\PropertyModel;
use cmf\controller\RestAdminBaseController;

/**
 * Description of PropertyController
 *
 * @author PC
 */
class PropertyController extends RestAdminBaseController{
    
    public function save(){
        $data = $this->request->post();
        $validate = [
            'attr_name'=>'require|length:2,10',
            'attr_value'=>'require|length:2,30',

        ];
        $msgs = [
            'attr_name.require'=>'名称不能为空',
            'attr_name.length'=>'名称长度2-10',
            'attr_value.require'=>'属性值不能为空',
            'attr_value.length'=>'属性值长度2-30',
        ];
        $result = $this->validate($data, $validate,$msgs);
        if($result!==true){
            $this->error($result,$data);
        }
        
        $model = new PropertyModel();
        $order = $model->where('item_id',$data['item_id'])->count();
        $data['item_order'] = $order+1;
        $model->insert($data);
        $this->success('保存成功');
    }
    
    public function down(){
        $id = $this->request->route('id/d');
        $this->change_order($id, 1);
    }
    
    public function up(){
        $id = $this->request->route('id/d');
        $this->change_order($id, -1);
    }
    
    private function change_order($id,$dict){
        $model = new PropertyModel();
        $prop = $model->where('id',$id)->find();
        $order = $prop->item_order;
        $order +=$dict;
        $model->where('item_id',$prop->item_id)->where('item_order',$order)->update(['item_order'=>$order-$dict]);
        $model->where('id',$id)->update(['item_order'=>$order]);
        $this->success('修改成功');
    }
    
    public function delete(){
        $model = new PropertyModel();
        $id = $this->request->route('id/d');
        $model->where('id',$id)->delete();
        $this->success('删除成功');
    }
}
